import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;

import org.eclipse.swt.SWT;
import org.eclipse.swt.browser.Browser;
import org.eclipse.swt.browser.LocationEvent;
import org.eclipse.swt.browser.LocationListener;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;

import com.gargoylesoftware.htmlunit.FailingHttpStatusCodeException;
import com.gargoylesoftware.htmlunit.StringWebResponse;
import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.html.HTMLParser;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
import com.gargoylesoftware.htmlunit.html.HtmlTable;
import com.gargoylesoftware.htmlunit.html.HtmlTableCell;
import com.gargoylesoftware.htmlunit.html.HtmlTableRow;
import com.gargoylesoftware.htmlunit.html.XHtmlPage;

 public class SWTBrowserTest 
 { 
	public static  XHtmlPage page3=null;
	 static long number=2487815L;
	 static boolean capchafound=false;
	 static boolean urlchanged=true;
     public static void main (String args []) throws Exception
     {
    	 Display display = new Display (); 
     Shell shell = new Shell (display); 
     shell.setText ("SWT Browser Test"); 
     shell.setSize (800,600); 
     final Text text = new Text (shell, SWT.BORDER); 
     text.setBounds (110,5,560,25); 
     Button button = new Button (shell, SWT.BORDER); 
     button.setBounds (680,5,100,25);        
     button.setText ("go"); 
     Label label = new Label (shell, SWT.LEFT); 
     label.setText ("Enter URL:"); 
     label.setBounds (5, 5, 100, 25);  
     final Browser browser = new Browser (shell, SWT.FILL); 
     browser.setBounds (5,30,780,560); 
     final WebClient webClient = new WebClient();
      HtmlPage page1=webClient.getPage("https://fjdclaims.phila.gov/phmuni/login.do");
      System.out.println("Got New Page : "+page1);
     browser.setUrl ("https://fjdclaims.phila.gov/phmuni/login.do"); 
     button.addListener (SWT.Selection, new Listener () 
     { 
         public void handleEvent (Event event) 
         { 
             String input = text.getText (). trim (); 
             if (input.length () == 0) return; 
             if (! input.startsWith ("http://")) 
             { 
                 text.setText (input); 
             } 
             browser.setUrl (input); 
         } 
     }); 
    
     shell.open (); 
	  		 System.out.println("Before creating web client ");
			 
			 System.out.println("After Creating webclient ");
			// final HtmlPage page1 = webClient.getPage("http://fjdclaims.phila.gov/phmuni/login.do");
		  //   System.out.println("Got New Page : "+ page1);
		   //  final List<?> loginPublicuser= page1.getByXPath("//input[@type='button' and @value='Login As Public User']");
		   //  System.out.println("Got Button : "+loginPublicuser.get(0));
		    // HtmlButtonInput loginasPublicUser=(HtmlButtonInput) loginPublicuser.get(0);
		   //  final HtmlPage page2=loginasPublicUser.click();
		   //  System.out.println("login Public User Clicked got another page.. : "+page2.toString());
			 try {
				 
			/*	 new java.util.Timer().schedule( 
					        new java.util.TimerTask() {
					            @SuppressWarnings("unchecked")
								@Override
					            public void run() {
					            	
					            }
					        },20000);*/
				System.out.println("Timer Task Created : ");
				 new java.util.Timer().schedule( 
					        new java.util.TimerTask() {
					            @SuppressWarnings("unchecked")
					        /*    Timer t=new Timer();
					            TimerTask tt=this;*/
								@Override
					            public void run() {
					            	
					            	
					                // your code here
					            	/* try {
										AccessController.doPrivileged(new PrivilegedExceptionAction() {
										     public Object run() throws Exception {
										        if(webClient.)
										       return null;
										     }
										 });
									} catch (PrivilegedActionException e1) {
										// TODO Auto-generated catch block
										e1.printStackTrace();
									}*/
					            	System.out.println("Inside Timer Task : ");
					               
					            	
					            	try {
					            		Display.getDefault().syncExec( new Runnable() {  @SuppressWarnings("deprecation")
										public void run() { 
					            			
											 try {
											//	 do
											    // {
												 //if(urlchanged)
											    //	{
											    	urlchanged=false;
													browser.setUrl("http://fjdclaims.phila.gov/phmuni/casedocket/caseDocket.do?caseID="+number);
													browser.addLocationListener(new LocationListener() {
													    public void changing(LocationEvent event)
													    {
													    	
													    }
													    

													    public void changed(LocationEvent event)
													    {
													    	text.setText(browser.getUrl());
													       // System.out.println("Location is: " + event.location);
													        try {
															//	System.out.println("In location browser get url value  : "+browser.getUrl());
																URL url = null;
																try {
																	url = new URL("https://fjdclaims.phila.gov/phmuni/login.do");
																} catch (MalformedURLException e) {
																	// TODO Auto-generated catch block
																	e.printStackTrace();
																}
																   //System.out.println("browser get Data : "+browser.getText());
																//	System.out.println("Browser URL  is : "+browser.getUrl());
																    StringWebResponse response = new StringWebResponse(browser.getText(), url);
																 //   System.out.println("response object is : "+response);
																    webClient.setJavaScriptEnabled(false);
																    try {
																		page3 = (XHtmlPage) HTMLParser.parseXHtml(response, webClient.getCurrentWindow());
																	//	System.out.println("page Title is : "+page3.getTitleText());
																		if(page3.getTitleText().equals("Case Captcha"))
																		{
																			capchafound=true;
																			//Thread.sleep(50000);
																			return;
																			
																		}
																		else
																			capchafound=false;
																	} catch (IOException e) {
																		// TODO Auto-generated catch block
																		e.printStackTrace();
																	}
																//   System.out.println("\n"+"page Link is : "+browser.getUrl());
																    final HtmlTable table = page3.getHtmlElementById("instanceTable");
																	//System.out.println("Got New Table : "+table);
																	for (final HtmlTableRow row : table.getRows()) {
																	  //  System.out.println("Found row");
																		System.out.println();
																	    for (final HtmlTableCell cell : row.getCells()) {
																	        System.out.print(cell.asText()+"\t" );
																	    }
																	}
																	final HtmlTable table1=page3.getHtmlElementById("docket-sheet");
																	//System.out.println("Got Another Table : "+table1);
																	for (final HtmlTableRow row : table1.getRows()) {
																	  //  System.out.println("Found row");
																		System.out.println();
																		final List<HtmlTableCell> cells=row.getCells();
																	    for (int i=0;i<cells.size()-1;i++) {
																	       System.out.print(cells.get(i).asText()+"\t");
																	    }
																
   }
															} catch (Exception e) {
																// TODO Auto-generated catch block
																//e.printStackTrace();
															}
															//	urlchanged=true;
													        if(capchafound)
													        {
													        	capchafound=false;
													        }
													        else{
																number=number+1;
																browser.setUrl("http://fjdclaims.phila.gov/phmuni/casedocket/caseDocket.do?caseID="+number);
													        }
													   }
													    
													});
													
													//System.out.println("URL Set is : "+browser.getUrl());
													//browser.setUrl("http://fjdclaims.phila.gov/phmuni/casedocket/caseDocket.do?caseID="+number);
													/*browser.addProgressListener(new ProgressListener() {
											            @Override
											            public void completed(ProgressEvent event) {
											              //  System.out.println("Page loaded");
											                try {
											                    Thread.sleep(2000);
											                } catch (InterruptedException e) {
											                    e.printStackTrace();
											                }
											                // Execute JavaScript in the browser
											            }
											            @Override
											            public void changed(ProgressEvent event) {
											            }
											        });*/
												//   System.out.println("Got New Page : "+page3);
												//	System.out.println("pag3 text is : "+page3.asText());
												//	List<HtmlAnchor> link = page3.getAnchors();
													//System.out.println("Got New Links : "+link.size());
												//	System.out.println("List of Links are : ");
													/*for(int i=0;i<link.size();i++)
														{
														System.out.println("item : "+i+" "+link.get(i));
														}*/
													
													}
											    
												//}
											//     }while(true);
												 // System.out.println("Got New Page : "+page3);
												//page3=webClient.getPage(browser.getText());
											 catch (FailingHttpStatusCodeException e) {
												// TODO Auto-generated catch block
												e.printStackTrace();
											
											} 

						            	} });
									
									/*HtmlPage page4=webClient.getPage("http://fjdclaims.phila.gov/phmuni/cms/search.do");
									System.out.println("got new page after clicking link  : "+page4);	
									List<?> searchBox=page4.getByXPath("//input[@type='text']");
									System.out.println("Got new text field : "+searchBox.size());
									for(int i=0;i<searchBox.size();i++)
										System.out.println(searchBox.get(1));*/
									
									
									} catch (FailingHttpStatusCodeException e) {
										// TODO Auto-generated catch block
										e.printStackTrace();
									} 
					            	
					            }
					        }, 
					        30000 
					);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			 while (! shell.isDisposed ()) { 
		         if (! display.readAndDispatch ()) 
		           display.sleep (); 
		       } 
		       display.dispose (); 
 
     }
 }